package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.to.es.SkuHasStockVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.fegin.CouponFeginService;
import com.atguigu.gulimall.product.fegin.SearchSaveFeginService;
import com.atguigu.gulimall.product.fegin.SkuHasStockFeginService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.skuvo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private SpuImagesService imagesService;
    @Autowired
    private ProductAttrValueService valueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeginService couponFeginService;

    @Autowired
    private  BrandService brandService;

    @Autowired
    private  CategoryService categoryService;

    @Autowired
    private SkuHasStockFeginService stockFeginService;

    @Autowired
    private SearchSaveFeginService searchSaveFeginService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //保存全部信息
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息  pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfo);
        baseMapper.insert(spuInfo);

        //2、保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        List<String> descImages = spuSaveVo.getDecript();
        spuInfoDesc.setSpuId(spuInfo.getId());
        spuInfoDesc.setDecript(String.join(",", descImages));
        descService.save(spuInfoDesc);

        //3、保存spu图片集  pms_spu_images
        List<String> images = spuSaveVo.getImages();
        if (images != null && images.size() > 0) {
            List<SpuImagesEntity> collect = images.stream().map(img -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfo.getId());
                spuImagesEntity.setImgUrl(img);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            imagesService.saveBatch(collect);
        }

        //4、spu规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            AttrEntity attrbyId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrId(attr.getAttrId());
            valueEntity.setSpuId(spuInfo.getId());
            valueEntity.setAttrName(attrbyId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        valueService.saveBatch(collect);


        //保存积分信息sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfo.getId());
        R r = couponFeginService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("保存积分信息失败");
        }
        //5、保存spu对应的sku所有信息
        //5.1 sku基本信息  pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            //private String skuName;
            //private BigDecimal price;
            //private String skuTitle;
            //private String skuSubtitle;
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1 sku基本信息  pms_sku_info
                skuInfoService.saveinfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();



                List<SkuImagesEntity> collect1 = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(img -> {
                    return StringUtils.isNotEmpty(img.getImgUrl());
                }).collect(Collectors.toList());
                //5.2 sku的图片集   pms_sku_images
                skuImagesService.saveBatch(collect1);

                //5.3 sku的销售属性  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect2 = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect2);
                //5.4 sku的优惠、满减信息 sms_sku_ladder、sms_sku_full_reduction、sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeginService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("sku的优惠、满减信息保存失败");
                    }
                }

            });
        }


    }

    //spu检索
    @Override
    public PageUtils queryPageAllspuinfoById(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }
    //商品上架
    @Override
    public void up(Long spuId) {
        //通过spuid查询skuinfo
        List<SkuInfoEntity> skuInfos = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIdList = skuInfos.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //TODO 查询规格属性
        List<ProductAttrValueEntity> attrValueList = valueService.listForSpuByspuId(spuId);
        List<Long> attrIds = attrValueList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //在attr中查询检索类型为1的数据
        List<Long> searchAttrIds=attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet=new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> attrs = attrValueList.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item->{
            SkuEsModel.Attr attr1 = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item,attr1);
            return  attr1;
        }).collect(Collectors.toList());

        //TODO hasStock 查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            List<SkuHasStockVo> skuHasStock = stockFeginService.getSkuHasStock(skuIdList);

            stockMap = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item->item.getHasStock()));
        }catch (Exception e){
            log.error("服务查询异常",e);
        }
        //遍历 封装sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfos.stream().map(item -> {
            //需要组装的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item,skuEsModel);
            //skuPrice、skuImg、
            skuEsModel.setSkuPrice(item.getPrice());
             skuEsModel.setSkuImg(item.getSkuDefaultImg());

             //库存
            if (finalStockMap ==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }
            //hotScore 热度评分
            skuEsModel.setHotScore(100L);
            /*
                private String brandName;
                private String brandImg;
                private String catalogName;
            */
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
             skuEsModel.setBrandName(brand.getName());
             skuEsModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(category.getName());


            /**
             * 规格属性
             * private Long attrId;
             * private String attrName;
             * private String attrValue;
             */
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 将collect发给esc
        R r = searchSaveFeginService.escSave(collect);
        if (r.getCode()==0){
            //调用成功修改转态码
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
            baseMapper.updateById(spuInfoEntity);
        }else {
            //TODO
            System.out.println("错误");
        }
    }

}